package com.common.sub.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.casicloud.manage.model.Authority;
import com.casicloud.manage.model.User;
import com.casicloud.manage.model.UserRole;
import com.casicloud.manage.service.AuthorityService;
import com.casicloud.manage.service.RoleService;
import com.casicloud.manage.service.UserRoleService;
import com.casicloud.manage.service.UserService;

public class ShiroAuthRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private UserRoleService userRoleService;
	
	@Autowired
	private AuthorityService authorityService;
	
	
	
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		
		@SuppressWarnings("unchecked")
		List<Integer> authoritylist =(List<Integer>) request.getSession().getAttribute("authority");
		
		if(authoritylist!=null&&authoritylist.size()>0){
			List<Authority> alist = authorityService.findByIds(authoritylist.toArray(new Integer[]{}));
			
			for(Authority au:alist){
				info.addStringPermission(au.getPermission());
			}
		}
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken arg0) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) arg0;
		User u = new User();
		u.setUsername(token.getUsername());
		u.setPassword(new String(token.getPassword()));
		u = userService.findByUserNameAndPassword(u);
		request.getSession().setAttribute("user", u);
		if(u!=null){
			UserRole ur = new UserRole();
			ur.setUserId(u.getId());
			List<UserRole> urlist = userRoleService.findRoleByList(ur);
			UserRoleList ul = new UserRoleList(urlist);
			request.getSession().setAttribute("menu", ul.getMenulist());
			request.getSession().setAttribute("authority", ul.getAuthoritylist());
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(token.getUsername(),token.getPassword(),getName());
			return  info;
		}
		throw new AuthenticationException();  
	}

}
